<template>
  <div style="height: 100%" ref="parentDiv">
    <div ref="openSeadragonElement" class="viewer" id="vieweropenDiv"></div>
    <!-- 放大标尺 -->
    <div id="zoomSlider" v-if="zoomSliderShow">
      <div class="bar" style="left: 3px; top: -36px" title="放大" @click="zoomIn">
        <i class="el-icon-plus"></i>
      </div>
      <div class="block" style="position: absolute">
        <div style="position: relative" class="zoomSlider">
          <el-slider v-model="viewZoom" @input="sliderZoom" vertical height="200px" :min="slideOption.min"
            :max="slideOption.max" :show-tooltip="false">
          </el-slider>
          <!-- 标尺 -->
          <!-- 左边标尺 -->
          <div class="zoomVlaueDiv-listContainers">
            <div class="zoomVlaueDiv-list">
              <div class="zoomVlaueDiv-right" v-for="(listItem, listIndex) in zoom2SlideArr" :key="listIndex"
                @click="setZoom(listItem.num)">
                {{ listItem.name }}
              </div>
            </div>
          </div>

          <div class="zoomVlaueDiv" :style="{ bottom: zoomVlaueDivB }">{{ zoomVlaue }}X</div>
        </div>
        <!-- <el-slider v-model="viewZoom" @input="sliderZoom" vertical :max="slideOption.max" :min="slideOption.min"
          height="200px" :marks="slideOption.masks">
        </el-slider> -->

      </div>
      <div class="bar" style="left: 3px; bottom: -36px" title="缩小" @click="zoomOut">
        <i class="el-icon-minus"></i>
      </div>
    </div>
    <div id="mapMeasure" v-if="compareScale" :style="{ width: measureClientWidth * 2 + 'px' }">
      <div class="mapMeasure_containers">
        <div class="ruler_begin"> </div>
        <div class="ruler_item"></div>
        <div class="ruler_item"></div>
        <div class="ruler_item"></div>
        <div class="ruler_item"></div>
        <div class="ruler_item"></div>

        <div class="ruler_nums">
          <span class="ruler_num ruler_num0">0</span>
          <span class="ruler_num ruler_num1">{{ measureNum / 5 }}</span>
          <span class="ruler_num ruler_num2">{{ measureNum * 2 / 5 }}</span>
          <span class="ruler_num ruler_num3">{{ measureNum * 3 / 5 }}</span>
          <span class="ruler_num ruler_num4">{{ measureNum * 4 / 5 }}</span>
          <span class="ruler_num ruler_num5">{{ measureNum * 5 / 5 }}<font class="meters">{{ measureUnit }}</font></span>
        </div>
      </div>
    </div>


    <remote-script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.min.js"></remote-script>
  </div>
</template>
<script>
// const Caman = require('caman');
import * as OpenSeadragon from 'openseadragon'
import * as paper from 'paper'
import * as _ from 'lodash'
import initPaper from './libs/openseadragon-paperjs-overlay'
import initImagingHelper from './libs/openseadragon-imaginghelper'
import scalebar from './libs/openseadragon-scalebar'
import Measuring from "./libs/measuring";
import Annotation from './libs/annotation'

let annotationsPoint = null
let lineWidth = 2
let pointSize = 10
let beginPencilPoint = null
let inBeginPoint = true
let paint = false

let segment, path
let movePath = false
let polygonStartPoint = null
let polygonAllpoints = []
import './libs/openseadragon-filtering'
import { os } from '@/libs/util'
let pixelsPerMeter = ''
export default {
  props: [
    'dziUrl',
    'annotationsData',
    'AiAnnotationsData',
    'pixelsPerMeter',
    'bgColor',
    'tiles',
    'type',
    'imageInfo'
  ],
  data() {
    return {
      gridline: false,
      discShow: true,
      dividScale: false,
      compareScale: true,//比例尺

      //左下角标尺
      measureClientWidth: 170,
      measureNum: 0,
      measureUnit: 'mm',

      zoomVlaue: 1,
      countNumber: '',
      drawGridSwitch: false,
      zoomSliderShow: true,
      discShow: true,
      // 绘制完成的AI标注
      AIAnnotations: [],
      // 绘制完成的标注
      annotations: [],
      // 测量标注
      measureAnnotations: [],

      editStatus: false,

      mycanvas: '',
      groupID: this.$route.query.groupID,
      pencilPoints: [],
      uploadUrl: '',
      messageForm: {
        content: ''
      },
      currentPath: null,
      redrawList: [],
      changeCurrent: null,
      changePoint: [],

      drawingLine: null,
      points: [],
      path: false,
      viewer: null,
      overlay: null,
      init: false,
      example: null,
      imagingHelper: null,
      lines: [
        [16000, 8000],
        [16000, 13000],
        [11000, 13000],
        [11000, 8000]
      ],
      // 画图相关
      pencilActive: false,
      pencilDrawing: false,

      polygonActive: false, //多边形标注
      polygonDrawing: false,

      annotationList: [],
      annotationPathList: [],
      annotationImageList: [],
      autoSetActive: false,
      autoSetClassInfo: {
        name: '',
        color: ''
      },

      editAnnotation: false,

      editPath: null,
      oldPath: null,
      editBeginSegment: null,
      editEndSegment: null,
      editPoints: [],

      aiAnnotations: [],

      currentChoseAIItem: null,

      drawingData: {
        type: '',
        points: []
      },

      tracker: null, // 事件处理器
      drawingAnnotation: null, // 当前正在绘制的标注
      currentEditAIPath: null, // 当前正在编辑的AI path 对象
      currentEditAIAnnotation: null, // 当前正在编辑的AI标注对象

      speed: 5, //移动速度
      status: '启动', //是否启动自动移动
      moveDirection: '', //自动移动的方向
      cameraMovement: '',
      activeClass: '', //按钮状态样式改变
      value: 0,

      infoPopoverVisible: true,
      navShown: true,

      // 放大倍率和滑动条对应表
      zoom2SlideValue: {
        1: 1,
        2: 2,
        4: 3,
        10: 4,
        20: 5,
        40: 6,
        80: 7
      },
      zoom2SlideArr: [
        {
          id: 1,
          name: '1X',
          num: 1,
        },
        {
          id: 2,
          name: '2X',
          num: 2,
        },
        {
          id: 3,
          name: '4X',
          num: 4,
        }, {
          id: 4,
          name: '10X',
          num: 10,
        }, {
          id: 5,
          name: '20X',
          num: 20,
        }, {
          id: 6,
          name: '40X',
          num: 40,
        }, {
          id: 7,
          name: '80X',
          num: 80,
        },

      ],
      viewZoom: 1, //放大缩小倍率
      Zoom: 1,
      gridPaths: [],
      zoomVlaueDivB: '0px',
      measuring: null, //刻度尺工具
      timeOut: null,
      isRotate: false,
      oldView: null //古老
    }
  },

  mounted() {
    this.__init()
    this.__initHandler()
    if (this.type === 'DZI') {
      this.open(this.dziUrl)
    }
    this.__drawAIAnnotations()
    this.__drawAnnotations()
    this.__initClickHandler()
    this.$refs.openSeadragonElement.onkeydown = function (e) {
      var e = event || window.event || arguments.callee.caller.arguments[0]
      if (e && (e.keyCode === 70 || e.keyCode === 82)) {
        // delete
        return false
      }
    }
    if (os().isPc) {
      this.zoomSliderShow = true
      this.discShow = true
    } else {
      this.zoomSliderShow = false
      this.discShow = false
    }
  },
  computed: {
    /**
     * 用来返回mask，max，min
     */
    slideOption() {
      let max = 1
      let min = 1
      const masks = {}

      _.keys(this.zoom2SlideValue).forEach(key => {
        if (max < this.zoom2SlideValue[key]) {
          max = this.zoom2SlideValue[key]
        }
        if (min > this.zoom2SlideValue[key]) {
          min = this.zoom2SlideValue[key]
        }
        masks[this.zoom2SlideValue[key]] = `${key}x`
      })

      return {
        max,
        min,
        masks
      }
    }
  },
  watch: {
    annotationsData() {
      this.__drawAnnotations()
    },
    AiAnnotationsData() {
      this.__drawAIAnnotations()
    }
  },
  methods: {
    //关闭小图例
    toggleNav() {
      if (this.navShown)
        this.viewer.navigator.element.style.display = "none";
      else
        this.viewer.navigator.element.style.display = "inline-block";
      this.navShown = !this.navShown;
    },
    jumpTOCase() {
      if (this.countNumber) {
        this.$emit('jumpToNumber', this.countNumber)
      } else {
        this.$message.info('请输入要跳转到的序列号')
      }
    },
    /**
     * 初始化 openseadron paper.js 等组件
     */
    __init() {
      window.OpenSeadragon = OpenSeadragon
      initPaper(OpenSeadragon, paper)
      paper.install(window)
      // console.log(this.type)
      initImagingHelper(OpenSeadragon, window.OpenSeadragonImaging || {})
      scalebar(OpenSeadragon)
      this.viewer = OpenSeadragon({
        id: 'openSeadragonId',
        element: this.$refs.openSeadragonElement,
        tileSources:
          this.type === 'IIIF'
            ? [
              {
                '@context': 'http://iiif.io/api/image/3/context.json',
                '@id': this.dziUrl,
                height: this.imageInfo.height,
                width: this.imageInfo.width,
                maxLevel: this.imageInfo.maxLevel,
                curScale: this.imageInfo.curScale,
                profile: ['http://iiif.io/api/image/3/level2.json'],
                protocol: 'http://iiif.io/api/image',
                tiles: this.tiles
              }
            ]
            : undefined,
        pixelsPerArrowPress: 0,
        crossOriginPolicy: true,

        panHorizontal: true,
        panVertical: true,
        /**
         * 缩略图相关f
         */
        showNavigator: true, // 是否展示缩略图
        navigatorId: '',
        navigatorAutoFade: false,
        navigatorMaintainSizeRatio: true,
        // navigatorId: '', //指定展示缩略图的 div。位置等属性配置将失效
        navigatorPosition: 'ABSOLUTE',
        // navigatorTop: '0px',
        // navigatorLeft:
        //   (document.documentElement.offsetWidth || document.body.offsetWidth) - 225 + 'px',
        navigatorTop: '25px',
        // (document.documentElement.offsetHeight || document.body.offsetHeight) - 180 + 'px',
        navigatorLeft: '25px',
        navigatorHeight: '140px',
        navigatorWidth: '180px',
        navigatorBorderColor: '#3a62d7',
        navigatorBackground: "#fff",
        // navigatorPosition: "TOP_Right",
        showNavigationControl: false,
        navigatorAutoFade: false,//停止交互淡出
        navigatorOpacity: 0.9,
        navigatorAutoResize: true,
        navigatorDisplayRegionColor: "red",
        /**
         * 控制按钮
         */
        // zoomInButton: 'zoom-in',
        // zoomOutButton: 'zoom-out',
        // homeButton: 'go-home',
        // fullPageButton: 'full-screen',
        // toolbar: 'toolbar',

        /**
         * 鼠标控制
         */
        // mouseNavEnabled: true,
        gestureSettingsMouse: {
          scrollToZoom: true,
          clickToZoom: false,
          dblClickToZoom: false
        }
      })
      //显示标尺
      //  console.log("openseadragon-scalebar" + this.pixelsPerMeter)
      this.scalebar = this.viewer.scalebar({
        pixelsPerMeter: this.pixelsPerMeter,
        type: 1,
        color: "red",
        barThickness: 6

      })
      let that = this


      this.overlay = this.viewer.paperjsOverlay()
      this.initImagingHelper = this.viewer.activateImagingHelper({
        onImageViewChanged: event => { }
      })
      //初始化刻度尺
      this.measuring = new Measuring(paper, this.viewer, this.pixelsPerMeter);
      //当查看器打开并加载一个或多个触发事件/增加标尺工具的事件
      this.timeOut = null  //this.__measuringDraw
      this.viewer.addHandler("update-viewport", function (data) {
        //  console.log("update-viewport____________==========" + that.dividScale)
        if (that.dividScale) { //放大缩小，才绘制
          //  console.log("9999")
          that.__measuringDraw()
        }

        // that.__measuringDraw()
        let objDiv = data.eventSource.scalebarInstance.divElt
        that.measureClientWidth = objDiv.size
        that.measureUnit = objDiv.innerText.slice(-2);
        that.measureNum = Number(objDiv.innerText.substr(0, objDiv.innerText.length - 3));
        // that.measuring.judmentRuler(that.dividScale, false);
        // that.measuring.judmentGrid(that.gridline);
        // that.measuring.lineRemove();
      });

    },
    /**
   * 刻度尺 网格线 的绘制事件方法
   */
    __measuringDraw() {
      // this.getRotation()

      if (this.viewer) { // 绘制
        // console.log("绘制~")
        this.measuring.reDraw(this.viewZoom, 0);
      }
      // let that = this
      // if (this.timeOut !== null) {
      //   clearTimeout(this.timeOut)
      // }
      // console.log("888888---------======")
      // this.timeOut = setTimeout(() => {
      //   if (that.viewer) {
      //     console.log("kaish  measur")
      //     that.measuring.reDraw(that.viewZoom, that.getRotation() % 360);
      //   }
      // }, 30)

    },
    //控制刻度尺 // 网格
    changeruleStatus() {
      //  console.log(this.getRotation() % 360)
      this.measuring.judmentRuler(this.dividScale, 0);
      if (this.dividScale) {//this.getRotation() % 360
        this.measuring.reDraw(this.viewZoom, 0);
        // this._rulerOrScale(true)
      } else {
        // this._rulerOrScale(false)
        this.measuring.lineRemove();

      }


    },
    changegridStatus() {

      if (this.gridline) {
        this._gridShow(true)
      } else {
        this._gridShow(false)
      }


    },
    //网格开关
    _gridShow(grid) {
      this.measuring.judmentGrid(grid);
      if (grid) {
        this.measuring.reDraw(this.viewZoom, 0);
      } else {
        this.measuring.lineRemove();
      }
    },
    //标尺比例尺开关
    _rulerOrScale(slideScale) {
      this.measuring.judmentRuler(slideScale, false);
    },
    //stop the grid drawing.
    stopDrawingGrid() {
      let _this = this
      _this.drawGridSwitch = false
      _this.gridPaths.forEach(item => {
        item.remove()
      })
    },
    //start the grid drawing.
    startDrawingGrid() {
      let _this = this
      _this.drawGridSwitch = true
      _this.drawGrid()
    },
    //对比度调节事件
    onContrastSlideChange(e) {
      let _this = this
      _this.viewer.setFilterOptions({
        filters: {
          processors: OpenSeadragon.Filters.CONTRAST(e / 100)
        }
      })
    },
    //亮度调节事件
    onLightSlideInput(e) {
      let _this = this
      _this.viewer.setFilterOptions({
        filters: {
          processors: OpenSeadragon.Filters.BRIGHTNESS(e - 50)
        }
      })
    },
    //gama调节事件
    onGamaSlideInput(e) {
      let _this = this
      if (e > 1) {
        _this.viewer.setFilterOptions({
          filters: {
            processors: OpenSeadragon.Filters.GAMMA(e / 100)
          }
        })
      }
    },
    getConvolution() {
      //矩阵规则，所有数相加得1；一般矩阵为3*3、5*5、7*7，只要保证为奇数即可，此处用最简单的3*3。
      var num = 5;
      var arr = [0, -num, 0, -num, num * 4 + 1, -num, 0, -num, 0]
      return OpenSeadragon.Filters.CONVOLUTION(arr)

    },
    //red调节事件
    onRedSlideInput(e) {
      let _this = this
      // console.log("开始")
      Caman.Store.put = function () { };
      this.viewer.setFilterOptions({
        filters: {
          processors: [
            //卷积（锐度）
            // _this.getConvolution(),
            function (context, callback) {
              // console.log(context.canvas)
              // console.log(e)
              Caman(context.canvas, function () {
                // //伽马
                // this.gamma(用户输入的数值);
                // //对比度
                // this.contrast(用户输入的数值);
                // //饱和度
                // this.saturation(用户输入的数值);
                //三通道颜色
                this.channels({
                  red: e.red,
                  green: e.green,
                  blue: e.blue
                });
                // console.log(e.red)
                //必须render
                this.render(callback);

              });

            }
          ]
        }
      })
    },

    //绘制方格
    drawGrid() {
      this.drawGridLines(21, 9, paper.view.bounds)
    },
    getRealScale(distance) {
      const firstPoint = paper.view.viewToProject(new paper.Point(0, distance))
      const secondPoint = paper.view.viewToProject(new paper.Point(0, 0))
      return firstPoint.getDistance(secondPoint)
    },
    drawGridLines(num_rectangles_wide, num_rectangles_tall, boundingRect) {
      this.gridPaths.forEach(item => {
        item.remove()
      })
      let width_per_rectangle = boundingRect.width / num_rectangles_wide
      let height_per_rectangle = boundingRect.height / num_rectangles_tall
      for (let i = 0; i <= num_rectangles_wide; i++) {
        let xPos = boundingRect.left + i * width_per_rectangle
        let topPoint = new paper.Point(xPos, boundingRect.top)
        let bottomPoint = new paper.Point(xPos, boundingRect.bottom)
        let aLine = new paper.Path.Line(topPoint, bottomPoint)
        aLine.strokeWidth = this.getRealScale(lineWidth) * 0.75
        aLine.strokeColor = '#d0d0d0'
        this.gridPaths.push(aLine)
      }
      for (let i = 0; i <= num_rectangles_tall; i++) {
        let yPos = boundingRect.top + i * height_per_rectangle
        let leftPoint = new paper.Point(boundingRect.left, yPos)
        let rightPoint = new paper.Point(boundingRect.right, yPos)
        let aLine = new paper.Path.Line(leftPoint, rightPoint)
        aLine.strokeWidth = this.getRealScale(lineWidth) * 0.75
        aLine.strokeColor = '#d0d0d0'
        this.gridPaths.push(aLine)
      }
    },

    //圆形标注
    beginCircleDrawing(status) {
      if (this.drawingAnnotation != null) {
        this.drawingAnnotation.hidePoints()
        this.drawingAnnotation.remove()
        this.drawingAnnotation = null
      }
      let _this = this
      if (status) {
        let beginPoint = null
        // 开始绘制
        const onMouseDown = function (event) {
          _this.viewer.panHorizontal = false
          _this.viewer.panVertical = false

          const point = view.viewToProject(event.position)

          const id = `${localStorage.getItem('login-users-id')}_${new Date().getTime()}`
          const color = _this.autoSetClassInfo.color
          const className = _this.autoSetClassInfo.name
          const saveUser = localStorage.getItem('login-users-id')
          const saveUserName = `${localStorage.getItem('login-users-name')}(您)`
          const type = 'circle'
          const name = _this.autoSetClassInfo.name

          _this.drawingAnnotation = new Annotation(view, paper, id, [], {
            lineWidth,
            pointSize,
            color,
            className,
            name,
            saveUser,
            saveUserName,
            type,
            pixelsPerMeter: _this.pixelsPerMeter
          })
          _this.drawingAnnotation.setDrawing(false)
          _this.drawingAnnotation.addPoint(point, true)
          //给正常区域增加虚线
          if (className === '正常区域') {
            _this.drawingAnnotation.addDottedLine(this.drawingAnnotation)
          }
          beginPoint = point
        }

        // 绘制
        const onMouseDrag = function (event) {
          const point = view.viewToProject(event.position)
          _this.drawingAnnotation.drawCircle(beginPoint, point)
          return false
        }

        // 结束绘制
        const onMouseUp = function (event) {
          const point = view.viewToProject(event.position)
          if (beginPoint.getDistance(point) <= 0) {
            console.error('没有移动，无法绘制')
            _this.drawingAnnotation.remove()
            _this.drawingAnnotation = null
            return false
          }

          _this.drawingAnnotation.drawCircle(beginPoint, point)

          // 判断是否被其他的标注包含
          let find = false
          _this.drawingAnnotation.setDrawing(false)
          _this.drawingAnnotation.hidePoints()
          _this.drawingAnnotation.initData()
          _this.drawingAnnotation.data.show = true

          if (!find) {
            _this.$emit('uploadAnnotation', this.drawingAnnotation)
            _this.annotations.push(this.drawingAnnotation)
          }

          _this.$emit('annotation-drawing-end', this.annotations)
          _this.drawingAnnotation = null

          _this.viewer.panHorizontal = true
          _this.viewer.panVertical = true
        }

        _this.tracker = new OpenSeadragon.MouseTracker({
          element: _this.viewer.canvas,
          pressHandler: _.bind(onMouseDown, this),
          dragHandler: _.bind(onMouseDrag, this),
          releaseHandler: _.bind(onMouseUp, this)
        })
        _this.tracker.setTracking(true)
      } else {
        if (_this.tracker) {
          _this.tracker.setTracking(false)
        }

        // 开启拖动
        _this.viewer.panHorizontal = true
        _this.viewer.panVertical = true
      }
    },
    /**
     * 初始化放大缩小事件监听
     */
    async __initHandler() {
      this.viewer.addHandler('zoom', data => {
        this.$emit('view-zoom', data.zoom)
        // console.log(data.zoom)
        this.zoomVlaue = data.zoom.toFixed(2);
        this.Zoom = data.zoom;
        const zoomMasks = _.sortBy(
          _.keys(this.zoom2SlideValue).map(item => {
            return parseInt(item)
          })
        )
        const index = _.sortedIndex(zoomMasks, data.zoom) - 1
        if (index >= zoomMasks.length - 1) {
          this.viewZoom = this.zoom2SlideValue[zoomMasks[zoomMasks.length - 1]]
          this.zoomVlaueDivB = '176px'
          return
        }
        if (index < 0) {
          this.viewZoom = this.zoom2SlideValue[zoomMasks[0]]
          this.zoomVlaueDivB = '-12px'
          return
        }

        const min = zoomMasks[index]
        const max = zoomMasks[index + 1]

        const scale = (data.zoom - min) / (max - min)
        // 因为真实值之间的差距都是1，这里就不做多余处理了
        this.viewZoom = this.zoom2SlideValue[min] + scale
        this.zoomVlaueDivB = ((this.viewZoom - 1) / (zoomMasks.length - 1) * 200 - 12) + 'px'
      })
      this.viewer.addHandler('open', () => {
        this.$emit('openseadragon-open')
      })
      this.viewer.addHandler('update-viewport', () => {
        if (this.drawingAnnotation && this.drawingAnnotation.setLineWidth) {
          this.drawingAnnotation.setLineWidth(lineWidth)
        }
        if (this.drawGridSwitch) {
          this.drawGrid()
        }
        for (let index = 0; index < this.annotations.length; index++) {
          //铅笔线
          if (this.annotations[index]) {
            this.annotations[index].setLineWidth(lineWidth)
          } else {
            console.error('error', index, this.annotations)
          }
        }

        for (let index = 0; index < this.AIAnnotations.length; index++) {
          //铅笔线
          if (this.AIAnnotations[index]) {
            this.AIAnnotations[index].setLineWidth(lineWidth)
          } else {
            console.error('error', index, this.AIAnnotations)
          }
        }

        for (let index = 0; index < this.measureAnnotations.length; index++) {
          if (this.measureAnnotations[index]) {
            this.measureAnnotations[index].setLineWidth(lineWidth)
          }
        }
        //边放大缩小边改变
        if (this.changeCurrent) {
          this.changeCurrent.strokeWidth = this.getRealDistance(lineWidth)
        }
        //多变形标注改变
        if (this.redrawPolygon) {
          this.redrawPolygon.strokeWidth = this.getRealDistance(lineWidth)
        }
        if (this.changePoint) {
          for (let index = 0; index < this.changePoint.length; index++) {
            this.changePoint[index].fillColor = '#ffffff'
          }
        }
        view.draw()
      })
    },
    /**
     * 处理没有任何操作选择时的鼠标事件
     * @param status boolean 是否开启
     */
    __initClickHandler() {
      const onMouseClick = function (event) {
        const pointClicked = view.viewToProject(event.position)
        // for (let i = 0; i < this.annotations.length; i++) {
        //     const hitResult = this.annotations[i].hitTest(pointClicked);
        //     if (!hitResult) {
        //         continue;
        //     }
        //     //this.annotationSelected(this.annotations[i]);
        //     break;
        // }
        for (let i = 0; i < this.AIAnnotations.length; i++) {
          const hitResult = this.__judge(pointClicked, this.AIAnnotations[i].points)
          // const hitResult = this.AIAnnotations[i].hitTest(pointClicked);
          if (!hitResult) {
            continue
          }
          this.annotationSelected(this.AIAnnotations[i])
          break
        }
      }

      new OpenSeadragon.MouseTracker({
        element: this.viewer.canvas,
        clickHandler: _.bind(onMouseClick, this)
      })
    },
    // 判断鼠标点击是否在图形内, 根据点击的点坐标与连续两个点交点计算
    __judge(dot, coordinates) {
      const x = dot.x,
        y = dot.y
      let crossNum = 0
      for (let i = 0; i < coordinates.length - 1; i++) {
        let start = coordinates[i]
        let end = coordinates[i + 1]

        // 起点、终点斜率不存在的情况
        if (start.x === end.x) {
          // 因为射线向右水平，此处说明不相交
          if (x > start.x) continue

          if (
            (end.y > start.y && y >= start.y && y <= end.y) ||
            (end.y < start.y && y >= end.y && y <= start.y)
          ) {
            crossNum++
          }
          continue
        }
        // 斜率存在的情况，计算斜率
        let k = (end.y - start.y) / (end.x - start.x)
        // 交点的x坐标
        let x0 = (y - start.y) / k + start.x
        // 因为射线向右水平，此处说明不相交
        if (x > x0) continue

        if (
          (end.x > start.x && x0 >= start.x && x0 <= end.x) ||
          (end.x < start.x && x0 >= end.x && x0 <= start.x)
        ) {
          crossNum++
        }
      }

      return crossNum % 2 === 1
    },
    __drawAIAnnotations() {
      if (this.AIAnnotations && this.AIAnnotations.length > 0) {
        this.AIAnnotations.forEach(anno => {
          anno.remove()
        })
      }
      const annotations = _.get(this, 'AiAnnotationsData', [])
      const aiAnnotations = []
      const aiInsideAnnotations = []
      const pathList = annotations.map(anno => {
        const points = _.get(anno, 'points', [])
        const color = _.get(anno, 'classToSet.color')
        const className = _.get(anno, 'classToSet.name')
        const id = anno.annotationId
        const annoObj = new Annotation(view, paper, id, points, {
          lineWidth,
          pointSize,
          color,
          className,
          pixelsPerMeter: this.pixelsPerMeter,
          fill: true,
          probablity: anno.probablity
        })
        if (anno.type === 'Inside') {
          aiInsideAnnotations.push(annoObj)
        } else {
          aiAnnotations.push(annoObj)
        }
        annoObj
          .draw()
          .setDrawing(false)
          .initData()
        return annoObj
      })
      aiInsideAnnotations.forEach(insideAnn => {
        for (let i = 0; i < aiAnnotations.length; i++) {
          // if (aiAnnotations[i].containTest(insideAnn)) {
          //     aiAnnotations[i].addChildren(insideAnn);
          //     break;
          // }
        }
      })
      this.AIAnnotations = aiAnnotations
      view.draw()
      // 发出绘制完成事件
      this.$emit('ai-annotation-drawing-end', this.AIAnnotations)
    },
    __drawAnnotations() {
      const oldList = this.annotations
      this.annotations = []

      const annotations = _.get(this, 'annotationsData', [])

      const pathList = annotations.map(anno => {
        const points = _.get(anno, 'points', [])
        const color = _.get(anno, 'classToSet.color')
        const className = _.get(anno, 'classToSet.name')
        const name = _.get(anno, 'name')
        const id = anno.annotationId
        const annoObj = new Annotation(view, paper, id, points, {
          lineWidth,
          pointSize,
          color,
          className,
          name,
          pixelsPerMeter: this.pixelsPerMeter,
          saveUser: anno.saveUser,
          saveUserName: anno.saveUserName,
          content: anno.content,
          type: anno.type,
          probablity: anno.probablity
        })
        if (anno.type == 'pencilLine') {
          annoObj
            .draw()
            .setDrawing(true)
            .initData()
        } else {
          annoObj
            .draw()
            .setDrawing(false)
            .initData()
        }
        const children = _.get(anno, 'children', [])
        //给正常区域增加虚线
        if (className === '正常区域') {
          annoObj.addDottedLine(annoObj)
        }
        children.forEach(child => {
          const childId = child.annotationId
          const childPoints = _.get(child, 'points', [])
          const childAnnoObj = new Annotation(view, paper, childId, childPoints, {
            lineWidth,
            pointSize,
            color,
            className,
            pixelsPerMeter: this.pixelsPerMeter,
            saveUser: anno.saveUser,
            saveUserName: anno.saveUserName,
            content: child.content
          })
          childAnnoObj
            .draw()
            .setDrawing(false)
            .initData()
          annoObj.addChildren(childAnnoObj)
        })
        annoObj.show = true
        return annoObj
      })
      view.draw()
      this.annotations = pathList
      if (oldList && oldList.length > 0) {
        oldList.forEach(oldAnnotation => {
          oldAnnotation.remove()
        })
      }
      // 发出绘制完成事件
      this.$emit('annotation-drawing-end', this.annotations)
      return pathList
    },

    /**
     * 开启或关闭
     * @param {string} annotationId
     * @param {boolean} edit 开启或者关闭
     * @param {boolean} recover 是否恢复，用于保存完从AI修改来的路径之后，恢复AI标注的显示
     */
    __annotationEdit(id, edit, recover) {
      const annotation = _.find(this.annotations, {
        id
      })
      if (!annotation) {
        return
      }
      let segment = null
      let path = null
      // 打开编辑模式
      if (!!edit) {
        this.currentEditAIPath = annotation.path
        this.currentEditAIAnnotation = annotation
        const onMouseDown = function (event) {
          const pointClicked = view.viewToProject(event.position)
          const hitResult = project.hitTest(pointClicked, {
            segments: true,
            stroke: true,
            fill: true,
            tolerance: 5
          })
          if (!hitResult) {
            segment = null
            path = null
            return
          }

          if (hitResult && hitResult.item == annotation.path) {
            if (event.originalEvent.shiftKey) {
              if (hitResult.type == 'segment') {
                hitResult.segment.remove()
              }
              return
            }

            this.viewer.panHorizontal = false
            this.viewer.panVertical = false

            this.editAnnotation = true

            if (hitResult) {
              path = hitResult.item
              if (hitResult.type == 'segment') {
                segment = hitResult.segment
              } else if (hitResult.type == 'stroke') {
                let location = hitResult.location
                segment = path.insert(location.index + 1, pointClicked)
                path.smooth()
              } else {
                segment = null
              }
            }
            movePath = false
            if (movePath) {
              project.activeLayer.addChild(hitResult.item)
            }
          }
        }
        const onMouseDrag = function (event) {
          const position = event.delta
          if (segment) {
            segment.point.x += this.getRealDistance(position.x)
            segment.point.y += this.getRealDistance(position.y)
            path.smooth()
          } else if (path && movePath) {
            path.position.x += this.getRealDistance(position.x)
            path.position.y += this.getRealDistance(position.y)
          }

          return true
        }
        this.tracker = new OpenSeadragon.MouseTracker({
          element: this.viewer.canvas,
          pressHandler: _.bind(onMouseDown, this),
          dragHandler: _.bind(onMouseDrag, this)
        })
        this.tracker.setTracking(true)
      } else {
        annotation.path.selected = false
        this.tracker.setTracking(false)
        if (recover) {
          // 恢复AI
          this.currentEditAIAnnotation.remove()
          this.currentEditAIAnnotation.draw().setDrawing(false)
        }
        this.viewer.panHorizontal = true
        this.viewer.panVertical = true
        this.currentEditAIPath = null
        this.currentEditAIAnnotation = null
      }
    },

    /**
     * 打开指定dzi的切片
     */
    open(dzi) {
      const that = this.viewer.open(dzi)
    },

    annotationSelected(annotation) {
      this.$emit('annotation-select', annotation)
    },

    /**
     * 重新绘制指定id的标注
     */
    redrawAnnotations(annotationId, classObj) {
      const annotation = _.find(this.redrawList, function (o) {
        return o.data && o.data.annotationId === annotationId
      })
      if (annotation) {
        annotation.setColorClass(classObj)
      }
      // 发出绘制完成事件
      this.$emit('annotation-drawing-end', this.redrawList)
      return this.redrawList
    },

    setAnnotationInfo(id, name, content, classType) {
      const annotation = _.find(this.annotations, {
        id
      })
      if (annotation) {
        annotation.setInfo(name, content)
        annotation.setColorClass(classType)
      }
      // 发出绘制完成事件
      this.$emit('annotation-drawing-end', this.annotations)
      return this.annotations
    },

    /**
     * 跳转到指定区域，会使用给定坐标的两倍大小作为可视区
     */
    jumpToArea(minX, minY, maxX, maxY) {
      //console.log('viewer', this.viewer.source)
      let oldBounds = this.viewer.viewport.getBounds(true)
      let width = maxX - minX
      let height = maxY - minY
      let proportion = oldBounds.width / oldBounds.height
      let pixelWidth = this.viewer.source.width
      let pixelHeight = this.viewer.source.height
      var maxLine = pixelWidth
      // this.annotationContentEditDialogVisible = true;
      //查询某一标注的具体信息
      // 放大两倍为可视区
      if (width / height > proportion) {
        width = 3 * width
        height = width / proportion
      } else {
        height = 3 * height
        width = height * proportion
      }

      var leftMove = (width - (maxX - minX)) / 2
      var topMove = (height - (maxY - minY)) / 2

      var x = minX - leftMove
      var y = minY - topMove

      width = width / maxLine
      height = width / proportion

      var newBounds = new OpenSeadragon.Rect(x / maxLine, y / maxLine, width, height)
      this.viewer.viewport.fitBounds(newBounds, true)
    },

    getImage(x, y, width, height) {
      const scale = window.devicePixelRatio

      const leftTop = new paper.Point(x, y)
      const rightBottom = new paper.Point(x + width, y + height)

      const realLeftTop = view.projectToView(leftTop)
      const realRightBottom = view.projectToView(rightBottom)
      const realWidth = realRightBottom.x - realLeftTop.x
      const realHeight = realRightBottom.y - realLeftTop.y

      const drawingFinalCanvas = document.createElement('canvas')
      drawingFinalCanvas.width = realWidth * scale
      drawingFinalCanvas.height = realHeight * scale

      const slideCanvas = this.viewer.canvas.children[0]
      const destCtx = drawingFinalCanvas.getContext('2d')
      destCtx.drawImage(
        slideCanvas,
        realLeftTop.x * scale,
        realLeftTop.y * scale,
        realWidth * scale,
        realHeight * scale,
        0,
        0,
        realWidth * scale,
        realHeight * scale
      )

      return drawingFinalCanvas.toDataURL('image/png')
    },

    setRotation(angle) {
      this.viewer.viewport.setRotation(angle)
      // this.viewer.rotate(angle)
    },
    // rotateEvent(angle) {
    //   console.log($("#vieweropenDiv canvas"))
    //   console.log(this.viewer)
    //   this.viewer.rotate(angle)
    //   console.log(this.viewer)

    // },
    getRotation() {
      return this.viewer.viewport.getRotation()
    },

    goHome() {
      this.viewer.viewport.goHome()
      this.viewer.viewport.setRotation(0)
    },

    /**
     * 如果是AI则新增标注；如果是标注者标注，则保存修改。
     */
    pathSubmission(annList) {
      const saveUser = _.get(this, 'currentChoseAIItem.data.saveUser')

      if (!saveUser) {
        return
      }

      const points = this.currentEditAIPath.segments.map(item => {
        return ['points', item.point.x, item.point.y]
      })

      if (saveUser === 'ai') {
        const data = {
          class: this.autoSetClassInfo,
          saveUser: localStorage.getItem('login-users-id'),
          annotationId: `${localStorage.getItem('login-users-id')}_${new Date().getTime()}`,
          createAt: new Date().getTime(),
          type: 'fromAI',
          name: this.autoSetClassInfo.name,
          show: true
        }

        this.__annotationEdit(this.currentEditAIAnnotation.data.annotationId, false, true)

        this.drawingAnnotation = new Annotation(
          view,
          paper,
          lineWidth,
          pointSize,
          this.pixelsPerMeter,
          data,
          points,
          data.class.color,
          []
        )
        this.drawingAnnotation.draw()
        this.drawingAnnotation.setDrawing(false)
        this.drawingAnnotation.hidePoints()
        this.drawingAnnotation.initData()
        this.$emit('uploadAnnotation', this.drawingAnnotation)
        this.redrawList.push(this.drawingAnnotation)
        this.$emit('annotation-drawing-end', this.redrawList)
      } else {
        const annotation = _.get(this, 'currentChoseAIItem.data')
        const path = _.get(this, 'currentChoseAIItem.path')
        this.$emit('update-info', {
          points,
          annotationId: annotation.annotationId
        })
        path.selected = false
        this.__annotationEdit(this.currentEditAIAnnotation.data.annotationId, false)
      }

      this.drawingAnnotation = null
    },

    //选择改变路径
    choseAnnotations(anno) {
      const id = anno.isChildren ? anno.perantId : anno.id
      let find = false
      for (let i = 0; i < this.annotations.length; i++) {
        if (id == this.annotations[i].id) {
          this.annotations[i].selected(true)
          this.currentChoseAIItem = this.annotations[i]
          this.__annotationEdit(this.currentChoseAIItem.id, true)
          find = true
        } else {
          this.annotations[i].selected(false)
        }
      }
      if (!find) {
        this.currentChoseAIItem = null
      }
    },
    checkAiAnnotations(path) {
      for (let i = 0; i < this.aiAnnotations.length; i++) {
        if (this.aiAnnotations === path) {
          return true
        }
      }

      return false
    },
    jumpToAnnotationArea(annotation) {
      const points = annotation.annotations.points
      let minX = points[0][1],
        maxX = points[0][1],
        minY = points[0][2],
        maxY = points[0][2]
      points.forEach(point => {
        if (point[1] < minX) minX = point[1]
        if (point[1] > maxX) maxX = point[1]
        if (point[2] < minY) minY = point[2]
        if (point[2] > maxY) maxY = point[2]
      })
      let width = maxX - minX
      let height = maxY - minY
      let oldBounds = this.viewer.viewport.getBounds(true)
      let proportion = oldBounds.width / oldBounds.height
      let pixelWidth = this.viewer.source.width
      let pixelHeight = this.viewer.source.height
      let maxLine = pixelWidth

      if (width / height > proportion) {
        width = 3 * width
        height = width / proportion
      } else {
        height = 3 * height
        width = height * proportion
      }

      let leftMove = (width - (maxX - minX)) / 2
      let topMove = (height - (maxY - minY)) / 2

      let x = minX - leftMove
      let y = minY - topMove

      width = width / maxLine
      height = width / proportion

      var newBounds = new OpenSeadragon.Rect(x / maxLine, y / maxLine, width, height)
      this.viewer.viewport.fitBounds(newBounds, false)
      // const pointList = [];
      // annotation.annotations.points.forEach( point => {
      //     // console.log(point);
      //     pointList.push(new Point(point[1], point[2]));
      // });
      // console.log('list', pointList);
    },
    autoSetClass(cls, active) {
      this.autoSetActive = active
      this.autoSetClassInfo = cls
      if (this.currentPath) {
        this.currentPath.style.strokeColor = cls.color
      }
      view.draw()
    },

    changeDrawClass(cls) {
      this.autoSetClassInfo = cls
    },
    beginArrowDrawing() {
      let lines = []
      let beginPoint = null
      let startPoint
      const getAngle = function (startX, startY, moveX, moveY) {
        let px = startX
        let py = startY
        let mx = moveX
        let my = moveY
        const x = Math.abs(px - mx)
        const y = Math.abs(py - my)
        const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))
        const cos = y / z
        const radina = Math.acos(cos)
        var angle = 180 / (Math.PI / radina)
        if (mx > px && my > py) {
          angle = 180 - angle
        }
        if (mx === px && my > py) {
          angle = 180
        }
        if (mx > px && my === py) {
          angle = 90
        }
        if (mx < px && my > py) {
          angle = 180 + angle
        }
        if (mx < px && my === py) {
          angle = 270
        }
        if (mx < px && my < py) {
          angle = 360 - angle
        }
        return angle
      }
      // 开始绘制
      const onMouseDown = function (event) {
        startPoint = event.position
        this.viewer.panHorizontal = false
        this.viewer.panVertical = false
        beginPoint = view.viewToProject(event.position)
      }
      // 结束绘制
      const onMouseUp = function (event) {
        if (
          Math.abs(event.position.x - startPoint.x) < 5 &&
          Math.abs(event.position.y - startPoint.y) < 5
        ) {
          this.$message.warning({
            message: '请按住鼠标左键拖动到标记位置'
          })
          return
        }
        let trianglePoint = view.viewToProject(event.position)
        let triangle = new paper.Path.RegularPolygon(
          trianglePoint,
          3,
          this.getRealScale(lineWidth) * 4
        )
        const angle = getAngle(startPoint.x, startPoint.y, event.position.x, event.position.y)
        triangle.fillColor = this.autoSetClassInfo.color
        let triangleSymbol = new Symbol(triangle)
        triangleSymbol.place(view.viewToProject(event.position)).rotate(angle)
        // .rotate(
        //     Math.atan2(
        //         trianglePoint.y - beginPoint.y,
        //         trianglePoint.x - beginPoint.x
        //     ) /
        //     0.017453292 -
        //     30
        // );
        lines = []
        this.viewer.panHorizontal = true
        this.viewer.panVertical = true
      }

      // 绘制
      const onMouseDrag = function (event) {
        lines.forEach(e => e.remove())
        let endPoint = view.viewToProject(event.position)
        let aLine = new paper.Path.Line(beginPoint, endPoint)
        aLine.strokeWidth = this.getRealScale(lineWidth)
        aLine.strokeColor = this.autoSetClassInfo.color
        lines.push(aLine)
        return false
      }

      this.tracker = new OpenSeadragon.MouseTracker({
        element: this.viewer.canvas,
        pressHandler: _.bind(onMouseDown, this),
        dragHandler: _.bind(onMouseDrag, this),
        releaseHandler: _.bind(onMouseUp, this)
      })
      this.tracker.setTracking(true)
    },
    beginPencilLineDrawing(status) {
      if (this.drawingAnnotation != null) {
        this.drawingAnnotation.hidePoints()
        this.drawingAnnotation.remove()
        this.drawingAnnotation = null
      }
      if (status) {
        // 取消拖动
        // this.viewer.panHorizontal = false;
        // this.viewer.panVertical = false;
        if (this.drawingAnnotation != null) {
          this.drawingAnnotation.hidePoints()
          this.drawingAnnotation.remove()
          this.drawingAnnotation = null
        }

        // 开始绘制
        const onMouseDown = function (event) {
          this.viewer.panHorizontal = false
          this.viewer.panVertical = false

          const point = view.viewToProject(event.position)

          const id = `${localStorage.getItem('login-users-id')}_${new Date().getTime()}`
          const color = this.autoSetClassInfo.color
          const className = this.autoSetClassInfo.name
          const saveUser = localStorage.getItem('login-users-id')
          const saveUserName = `${localStorage.getItem('login-users-name')}(您)`
          const type = 'pencilLine'
          const name = this.autoSetClassInfo.name

          this.drawingAnnotation = new Annotation(view, paper, id, [], {
            lineWidth,
            pointSize,
            color,
            className,
            name,
            saveUser,
            saveUserName,
            type,
            pixelsPerMeter: this.pixelsPerMeter
          })
          this.drawingAnnotation.draw()
          this.drawingAnnotation.addPoint(point, true)
          //给正常区域增加虚线
          if (className === '正常区域') {
            this.drawingAnnotation.addDottedLine(this.drawingAnnotation)
          }
        }

        // 结束绘制
        const onMouseUp = function (event) {
          const point = view.viewToProject(event.position)
          this.drawingAnnotation.addPoint(point)
          // 点太少舍弃
          if (this.drawingAnnotation.points.length < 30) {
            this.drawingAnnotation.hidePoints()
            this.drawingAnnotation.remove()
            this.drawingAnnotation = null
            return
          }
          // 判断是否被其他的标注包含
          let find = false
          // for (let i = 0; i < this.annotations.length; i++) {
          //     if (this.annotations[i].containTest(this.drawingAnnotation)) {
          //         find = true;
          //         this.annotations[i].addChildren(this.drawingAnnotation);
          //         this.$emit('after-add-child-annotaion', this.annotations[i].id, this
          //             .drawingAnnotation);
          //         break;
          //     }
          // }
          this.drawingAnnotation.setDrawing(true)
          this.drawingAnnotation.hidePoints()
          this.drawingAnnotation.initData()
          this.drawingAnnotation.data.show = true

          if (!find) {
            this.$emit('uploadAnnotation', this.drawingAnnotation)
            this.annotations.push(this.drawingAnnotation)
          }

          this.$emit('annotation-drawing-end', this.annotations)
          this.drawingAnnotation = null

          this.viewer.panHorizontal = true
          this.viewer.panVertical = true
        }

        // 绘制
        const onMouseDrag = function (event) {
          const point = view.viewToProject(event.position)
          this.drawingAnnotation.addPoint(point)

          return false
        }

        this.tracker = new OpenSeadragon.MouseTracker({
          element: this.viewer.canvas,
          pressHandler: _.bind(onMouseDown, this),
          dragHandler: _.bind(onMouseDrag, this),
          releaseHandler: _.bind(onMouseUp, this)
        })
        this.tracker.setTracking(true)
      } else {
        if (this.tracker) {
          this.tracker.setTracking(false)
        }

        // 开启拖动
        this.viewer.panHorizontal = true
        this.viewer.panVertical = true
      }
    },
    beginPencilDrawing(status) {
      if (this.drawingAnnotation != null) {
        this.drawingAnnotation.hidePoints()
        this.drawingAnnotation.remove()
        this.drawingAnnotation = null
      }
      if (status) {
        // 取消拖动
        // this.viewer.panHorizontal = false;
        // this.viewer.panVertical = false;
        if (this.drawingAnnotation != null) {
          this.drawingAnnotation.hidePoints()
          this.drawingAnnotation.remove()
          this.drawingAnnotation = null
        }

        // 开始绘制
        const onMouseDown = function (event) {
          this.viewer.panHorizontal = false
          this.viewer.panVertical = false

          const point = view.viewToProject(event.position)

          const id = `${localStorage.getItem('login-users-id')}_${new Date().getTime()}`
          const color = this.autoSetClassInfo.color
          const className = this.autoSetClassInfo.name
          const saveUser = localStorage.getItem('login-users-id')
          const saveUserName = `${localStorage.getItem('login-users-name')}(您)`
          const type = 'pencil'
          const name = this.autoSetClassInfo.name

          this.drawingAnnotation = new Annotation(view, paper, id, [], {
            lineWidth,
            pointSize,
            color,
            className,
            name,
            saveUser,
            saveUserName,
            type,
            pixelsPerMeter: this.pixelsPerMeter
          })
          this.drawingAnnotation.draw()
          this.drawingAnnotation.addPoint(point, true)
          //给正常区域增加虚线
          if (className === '正常区域') {
            this.drawingAnnotation.addDottedLine(this.drawingAnnotation)
          }
        }

        // 结束绘制
        const onMouseUp = function (event) {
          const point = view.viewToProject(event.position)
          this.drawingAnnotation.addPoint(point)
          // 点太少舍弃
          if (this.drawingAnnotation.points.length < 30) {
            this.drawingAnnotation.hidePoints()
            this.drawingAnnotation.remove()
            this.drawingAnnotation = null
            return
          }
          // 判断是否被其他的标注包含
          let find = false
          // for (let i = 0; i < this.annotations.length; i++) {
          //     if (this.annotations[i].containTest(this.drawingAnnotation)) {
          //         find = true;
          //         this.annotations[i].addChildren(this.drawingAnnotation);
          //         this.$emit('after-add-child-annotaion', this.annotations[i].id, this
          //             .drawingAnnotation);
          //         break;
          //     }
          // }
          this.drawingAnnotation.setDrawing(false)
          this.drawingAnnotation.hidePoints()
          this.drawingAnnotation.initData()
          this.drawingAnnotation.data.show = true

          if (!find) {
            this.$emit('uploadAnnotation', this.drawingAnnotation)
            this.annotations.push(this.drawingAnnotation)
          }

          this.$emit('annotation-drawing-end', this.annotations)
          this.drawingAnnotation = null

          this.viewer.panHorizontal = true
          this.viewer.panVertical = true
        }

        // 绘制
        const onMouseDrag = function (event) {
          const point = view.viewToProject(event.position)
          this.drawingAnnotation.addPoint(point)

          return false
        }

        this.tracker = new OpenSeadragon.MouseTracker({
          element: this.viewer.canvas,
          pressHandler: _.bind(onMouseDown, this),
          dragHandler: _.bind(onMouseDrag, this),
          releaseHandler: _.bind(onMouseUp, this)
        })
        this.tracker.setTracking(true)
      } else {
        if (this.tracker) {
          this.tracker.setTracking(false)
        }

        // 开启拖动
        this.viewer.panHorizontal = true
        this.viewer.panVertical = true
      }
    },
    beginPolygonDrawing(status) {
      if (this.drawingAnnotation != null) {
        this.drawingAnnotation.hidePoints()
        this.drawingAnnotation.remove()
        this.drawingAnnotation = null
      }
      if (status) {
        // 取消拖动
        this.viewer.panHorizontal = false
        this.viewer.panVertical = false

        const onMouseClick = function (event) {
          const point = view.viewToProject(event.position)

          if (this.drawingAnnotation == null || !this.drawingAnnotation) {
            const id = `${localStorage.getItem('login-users-id')}_${new Date().getTime()}`
            const color = this.autoSetClassInfo.color
            const className = this.autoSetClassInfo.name
            const saveUser = localStorage.getItem('login-users-id')
            const saveUserName = `${localStorage.getItem('login-users-name')}(您)`
            const type = 'polygon'
            const name = this.autoSetClassInfo.name

            this.drawingAnnotation = new Annotation(view, paper, id, [], {
              lineWidth,
              pointSize,
              color,
              className,
              name,
              saveUser,
              saveUserName,
              type,
              pixelsPerMeter: this.pixelsPerMeter
            })
            this.drawingAnnotation.draw()
            this.drawingAnnotation.addPoint(point, true)
            //给正常区域增加虚线
            if (className === '正常区域') {
              this.drawingAnnotation.addDottedLine(this.drawingAnnotation)
            }
            return
          }

          const hitItem = project.hitTest(point)
          this.drawingAnnotation.addPoint(point, true)
        }
        const onDblClick = function (event) {
          const point = view.viewToProject(event.position)
          this.drawingAnnotation.addPoint(point)

          // 判断是否被其他的标注包含
          let find = false
          // for (let i = 0; i < this.annotations.length; i++) {
          //     if (this.annotations[i].containTest(this.drawingAnnotation)) {
          //         find = true;
          //         this.annotations[i].addChildren(this.drawingAnnotation);
          //         this.$emit('after-add-child-annotaion', this.annotations[i].id, this
          //             .drawingAnnotation);
          //         break;
          //     }
          // }

          this.drawingAnnotation.setDrawing(false)
          this.drawingAnnotation.hidePoints()
          this.drawingAnnotation.initData()
          this.drawingAnnotation.data.show = true

          if (!find) {
            this.$emit('uploadAnnotation', this.drawingAnnotation)
            this.annotations.push(this.drawingAnnotation)
          }

          this.$emit('annotation-drawing-end', this.annotations)
          this.drawingAnnotation = null

          this.viewer.panHorizontal = true
          this.viewer.panVertical = true
        }

        this.tracker = new OpenSeadragon.MouseTracker({
          element: this.viewer.canvas,
          dblClickHandler: _.bind(onDblClick, this),
          clickHandler: _.bind(onMouseClick, this)
        })
        this.tracker.setTracking(true)
      } else {
        if (this.tracker) {
          this.tracker.setTracking(false)
        }

        // 开启拖动
        this.viewer.panHorizontal = true
        this.viewer.panVertical = true
      }
    },

    beginRectangleDrawing(status) {
      if (this.drawingAnnotation != null) {
        this.drawingAnnotation.hidePoints()
        this.drawingAnnotation.remove()
        this.drawingAnnotation = null
      }
      if (status) {
        if (this.drawingAnnotation != null) {
          this.drawingAnnotation.hidePoints()
          this.drawingAnnotation.remove()
          this.drawingAnnotation = null
        }

        let beginPoint = null

        // 开始绘制
        const onMouseDown = function (event) {
          this.viewer.panHorizontal = false
          this.viewer.panVertical = false

          const point = view.viewToProject(event.position)

          const id = `${localStorage.getItem('login-users-id')}_${new Date().getTime()}`
          const color = this.autoSetClassInfo.color
          const className = this.autoSetClassInfo.name
          const saveUser = localStorage.getItem('login-users-id')
          const saveUserName = `${localStorage.getItem('login-users-name')}(您)`
          const type = 'rectangle'
          const name = this.autoSetClassInfo.name

          this.drawingAnnotation = new Annotation(view, paper, id, [], {
            lineWidth,
            pointSize,
            color,
            className,
            name,
            saveUser,
            saveUserName,
            type,
            pixelsPerMeter: this.pixelsPerMeter
          })
          this.drawingAnnotation.draw()
          this.drawingAnnotation.setDrawing(false)
          this.drawingAnnotation.addPoint(point, true)
          //给正常区域增加虚线
          if (className === '正常区域') {
            this.drawingAnnotation.addDottedLine(this.drawingAnnotation)
          }
          beginPoint = point
        }

        // 绘制
        const onMouseDrag = function (event) {
          const point = view.viewToProject(event.position)

          const rightTop = new Point(point.x, beginPoint.y)
          const leftBottom = new Point(beginPoint.x, point.y)

          this.drawingAnnotation.changePoints([beginPoint, rightTop, point, leftBottom])

          return false
        }

        // 结束绘制
        const onMouseUp = function (event) {
          const point = view.viewToProject(event.position)
          const rightTop = new Point(point.x, beginPoint.y)
          const leftBottom = new Point(beginPoint.x, point.y)

          if (rightTop.getDistance(leftBottom) <= 0) {
            console.error('没有移动，无法绘制')
            this.drawingAnnotation.remove()
            this.drawingAnnotation = null
            return false
          }

          this.drawingAnnotation.changePoints([beginPoint, rightTop, point, leftBottom])

          // 判断是否被其他的标注包含
          let find = false
          // for (let i = 0; i < this.annotations.length; i++) {
          //     if (this.annotations[i].containTest(this.drawingAnnotation)) {
          //         find = true;
          //         this.annotations[i].addChildren(this.drawingAnnotation);
          //         this.$emit('after-add-child-annotaion', this.annotations[i].id, this
          //             .drawingAnnotation);
          //         break;
          //     }
          // }

          this.drawingAnnotation.setDrawing(false)
          this.drawingAnnotation.hidePoints()
          this.drawingAnnotation.initData()
          this.drawingAnnotation.data.show = true

          if (!find) {
            this.$emit('uploadAnnotation', this.drawingAnnotation)
            this.annotations.push(this.drawingAnnotation)
          }

          this.$emit('annotation-drawing-end', this.annotations)
          this.drawingAnnotation = null

          this.viewer.panHorizontal = true
          this.viewer.panVertical = true
        }

        this.tracker = new OpenSeadragon.MouseTracker({
          element: this.viewer.canvas,
          pressHandler: _.bind(onMouseDown, this),
          dragHandler: _.bind(onMouseDrag, this),
          releaseHandler: _.bind(onMouseUp, this)
        })
        this.tracker.setTracking(true)
      } else {
        if (this.tracker) {
          this.tracker.setTracking(false)
        }

        // 开启拖动
        this.viewer.panHorizontal = true
        this.viewer.panVertical = true
      }
    },

    beginMeasuringDistance(status) {
      if (this.drawingAnnotation != null) {
        this.drawingAnnotation.hidePoints()
        this.drawingAnnotation.remove()
        this.drawingAnnotation = null
      }
      if (status) {
        // 取消拖动
        this.viewer.panHorizontal = false
        this.viewer.panVertical = false

        let distance = 0 // pixel
        let lastPoint = null

        const onMouseClick = function (event) {
          const point = view.viewToProject(event.position)

          if (this.drawingAnnotation == null || !this.drawingAnnotation) {
            const id = `${localStorage.getItem('login-users-id')}_${new Date().getTime()}`
            const color = '#0000b4'
            const className = '测距'
            const saveUser = localStorage.getItem('login-users-id')
            const saveUserName = `${localStorage.getItem('login-users-name')}(您)`
            const type = 'distance'
            const name = '测距'

            this.drawingAnnotation = new Annotation(view, paper, id, [], {
              lineWidth,
              pointSize,
              color,
              className,
              name,
              saveUser,
              saveUserName,
              type,
              pixelsPerMeter: this.pixelsPerMeter
            })
            this.drawingAnnotation.draw()
            this.drawingAnnotation.addPoint(point, true)
            lastPoint = point
            return
          }

          if (lastPoint) {
            distance += point.getDistance(lastPoint)
          }
          lastPoint = point

          const hitItem = project.hitTest(point)
          this.drawingAnnotation.addPoint(point, true)
        }

        const onDblClick = function (event) {
          const point = view.viewToProject(event.position)
          this.drawingAnnotation.addPoint(point)

          this.drawingAnnotation.data.show = true
          this.drawingAnnotation.hidePoints()
          this.drawingAnnotation.initData()

          this.measureAnnotations.push(this.drawingAnnotation)
          if (lastPoint) {
            distance += point.getDistance(lastPoint)
          }

          const distanceMeter = `${((distance / this.pixelsPerMeter) * 1000000).toFixed(2)} μm`

          this.drawingAnnotation.setText(distanceMeter)
          this.$emit('measure-annotation-drawing-end', this.measureAnnotations)
          this.drawingAnnotation = null

          this.viewer.panHorizontal = true
          this.viewer.panVertical = true

          distance = 0
          lastPoint = null
        }

        this.tracker = new OpenSeadragon.MouseTracker({
          element: this.viewer.canvas,
          dblClickHandler: _.bind(onDblClick, this),
          clickHandler: _.bind(onMouseClick, this)
        })
        this.tracker.setTracking(true)
      } else {
        if (this.tracker) {
          this.tracker.setTracking(false)
        }

        this.drawingAnnotation = null

        // 开启拖动
        this.viewer.panHorizontal = true
        this.viewer.panVertical = true
      }
    },

    beginMeasuringArea(status) {
      if (this.drawingAnnotation != null) {
        this.drawingAnnotation.hidePoints()
        this.drawingAnnotation.remove()
        this.drawingAnnotation = null
      }
      if (status) {
        // 取消拖动
        this.viewer.panHorizontal = false
        this.viewer.panVertical = false

        const onMouseClick = function (event) {
          const point = view.viewToProject(event.position)

          if (this.drawingAnnotation == null || !this.drawingAnnotation) {
            const id = `${localStorage.getItem('login-users-id')}_${new Date().getTime()}`
            const color = '#0000b4'
            const className = '测距'
            const saveUser = localStorage.getItem('login-users-id')
            const saveUserName = `${localStorage.getItem('login-users-name')}(您)`
            const type = 'distance'
            const name = '测距'

            this.drawingAnnotation = new Annotation(view, paper, id, [], {
              lineWidth,
              pointSize,
              color,
              className,
              name,
              saveUser,
              saveUserName,
              type,
              pixelsPerMeter: this.pixelsPerMeter,
              fill: true
            })

            this.drawingAnnotation.draw()
            this.drawingAnnotation.addPoint(point, true)
            this.drawingAnnotation.path.closed = true
            return
          }

          const hitItem = project.hitTest(point)
          this.drawingAnnotation.addPoint(point, false)
        }

        const onDblClick = function (event) {
          const point = view.viewToProject(event.position)
          this.drawingAnnotation.addPoint(point)

          this.drawingAnnotation.data.show = true
          this.drawingAnnotation.hidePoints()
          this.drawingAnnotation.initData()

          this.measureAnnotations.push(this.drawingAnnotation)

          const area = _.get(this, 'drawingAnnotation.data.area')

          this.drawingAnnotation.setText(
            area ? `${(area * 1000000 * 1000000).toFixed(4)} μm²` : '获取失败'
          )

          this.$emit('measure-annotation-drawing-end', this.measureAnnotations)
          this.drawingAnnotation = null

          this.viewer.panHorizontal = true
          this.viewer.panVertical = true
        }

        this.tracker = new OpenSeadragon.MouseTracker({
          element: this.viewer.canvas,
          dblClickHandler: _.bind(onDblClick, this),
          clickHandler: _.bind(onMouseClick, this)
        })
        this.tracker.setTracking(true)
      } else {
        if (this.tracker) {
          this.tracker.setTracking(false)
        }

        this.drawingAnnotation = null

        // 开启拖动
        this.viewer.panHorizontal = true
        this.viewer.panVertical = true
      }
    },

    panToggle(status) {
      this.viewer.panHorizontal = status
      this.viewer.panVertical = status
    },

    getRealDistance(distance) {
      return view.viewToProject(new Point(0, distance)).y - view.viewToProject(new Point(0, 0)).y
    },

    removeAnnotation(id, pid) {
      if (pid) {
        for (let i = 0; i < this.annotations.length; i++) {
          if (this.annotations[i].id === pid) {
            for (let j = 0; j < this.annotations[i].children.length; j++) {
              const child = this.annotations[i].children[j]
              if (child.id === id) {
                child.remove()
                _.pullAt(this.annotations[i].children, j)
                break
              }
            }
            break
          }
        }
      } else {
        for (let i = 0; i < this.annotations.length; i++) {
          if (this.annotations[i].id === id) {
            this.annotations[i].remove()
            _.pullAt(this.annotations, i)
            break
          }
        }
      }

      this.$emit('annotation-drawing-end', this.annotations)
      return this
    },

    removeAllAnnotation() {
      const aiAnnotations = []
      this.redrawList.forEach(item => {
        if (item.data.saveUser === 'ai') {
          aiAnnotations.push(item)
        } else {
          item.remove()
        }
      })
      this.redrawList = aiAnnotations
      this.$emit('annotation-drawing-end', this.redrawList)
      return this
    },

    removeAllMeasureAnnotations() {
      this.measureAnnotations.forEach(item => {
        item.remove()
      })
    },

    clear() {
      if (beginPencilPoint) beginPencilPoint.remove()
      if (polygonAllpoints && polygonAllpoints.length && polygonAllpoints.length > 0) {
        polygonAllpoints.forEach(po => po.remove())
      }
      this.points = []
      this.annotationList = []
      if (this.annotationPathList.length && this.annotationPathList.length > 0) {
        this.annotationPathList.forEach(pa => pa.remove())
      }
      if (this.currentPath) this.currentPath.remove()
      view.draw()
    },

    //缩放到相应的数值
    zoomJumpTo(num) {
      this.viewer.viewport.zoomTo(num)
    },
    //放大
    zoomIn() {

      const newZoom = this.Zoom + 1
      //console.log(newZoom)
      if (newZoom < 80) {
        this.viewer.viewport.zoomTo(newZoom)
      }
    },

    //缩小
    zoomOut() {
      const newZoom = this.Zoom - 1
      if (newZoom > 0.5) {
        this.viewer.viewport.zoomTo(newZoom)
      }
    },
    setZoom(val) {
      this.viewer.viewport.zoomTo(val)
      const zoomMasks = _.sortBy(
        _.keys(this.zoom2SlideValue).map(item => {
          return parseInt(item)
        })
      )
      // console.log(this.viewZoom - 1)
      this.zoomVlaueDivB = ((this.viewZoom - 1) / (zoomMasks.length - 1) * 200 - 12) + 'px'
    },
    //通过滑块缩放
    sliderZoom(val) {
      const val2Zoom = {}
      const zoomMasks = _.sortBy(
        _.keys(this.zoom2SlideValue).map(item => {
          return parseInt(item)
        })
      )
      _.keys(this.zoom2SlideValue).forEach(key => {
        val2Zoom[this.zoom2SlideValue[key]] = parseInt(key)
      })
      if (val2Zoom[val]) {
        this.viewer.viewport.zoomTo(val2Zoom[val])
        return
      }
      // console.log("值" + this.viewZoom)

      this.zoomVlaueDivB = ((this.viewZoom - 1) / (zoomMasks.length - 1) * 200 - 12) + 'px'
    },
    moveEvent(data) {
      this.moveDirection = data.moveDirection
      this.status = data.status
      this.speed = data.speed
      if (data.evetType == "start") {
        this.ifMove()
      } else if (data.evetType == 'modeType') {
        this.ifMove()
      } else if (data.evetType == 'stepIsStart') {
        this.setMove()
      }
    },
    setMove() { //手动移动
      const fps = 20
      const angel = 0
      const oldBound = this.viewer.viewport.getBounds()

      // 计算每次刷新时的平均位移
      let shiftY = 0
      if (this.moveDirection === 'up') {
        shiftY = (-1 * oldBound.height) / fps
      }
      if (this.moveDirection === 'down') {
        shiftY = oldBound.height / fps
      }

      let shiftX = 0
      if (this.moveDirection === 'left') {
        shiftX = (-1 * oldBound.height) / fps
      }
      if (this.moveDirection === 'right') {
        shiftX = oldBound.height / fps
      }
      const rad = (2 * Math.PI * angel) / 360
      const currentX = (this.speed / 100) * (shiftX * Math.cos(rad) + shiftY * Math.sin(rad))
      const currentY = (this.speed / 100) * (shiftY * Math.cos(rad) - shiftX * Math.sin(rad))

      const newBound = new OpenSeadragon.Rect(
        oldBound.x + currentX,
        oldBound.y + currentY,
        oldBound.width,
        oldBound.height,
        oldBound.degrees
      )
      this.viewer.viewport.fitBounds(newBound, false)
    },
    //自动移动上下左右，停止与启动
    ifMove() {
      if (this.moveDirection) {
        if (this.status === '停止') {
          clearInterval(this.cameraMovement)
        } else {
          const fps = 20
          const angel = 0
          const intervalTime = parseInt(1000 / fps)
          this.cameraMovement = setInterval(() => {
            const oldBound = this.viewer.viewport.getBounds()

            // 计算每次刷新时的平均位移
            let shiftY = 0
            if (this.moveDirection === 'up') {
              shiftY = (-1 * oldBound.height) / fps
            }
            if (this.moveDirection === 'down') {
              shiftY = oldBound.height / fps
            }

            let shiftX = 0
            if (this.moveDirection === 'left') {
              shiftX = (-1 * oldBound.height) / fps
            }
            if (this.moveDirection === 'right') {
              shiftX = oldBound.height / fps
            }
            const rad = (2 * Math.PI * angel) / 360
            const currentX = (this.speed / 100) * (shiftX * Math.cos(rad) + shiftY * Math.sin(rad))
            const currentY = (this.speed / 100) * (shiftY * Math.cos(rad) - shiftX * Math.sin(rad))

            const newBound = new OpenSeadragon.Rect(
              oldBound.x + currentX,
              oldBound.y + currentY,
              oldBound.width,
              oldBound.height,
              oldBound.degrees
            )
            this.viewer.viewport.fitBounds(newBound, false)
          }, intervalTime)
        }
      } else {
        console.log('请选择方向')
      }
    },

  }
}
</script>

<style>
#mapMeasure {
  position: absolute;
  bottom: 60px;
  left: 20px;
  height: 14px;
  transition: width .2s;
}

.mapMeasure_containers {
  position: relative;
  width: 100%;
  height: 14px;
}

.ruler_nums {
  position: absolute;
  top: 18px;
  left: -2px;
  width: 100%;
  font-weight: 700;
}

.ruler_num {
  position: absolute;
  margin-left: -10%;
  width: 20%;
  font-size: 14px;
  font-family: "微软雅黑";
  color: rgb(58, 98, 215);
  top: 0;
  text-align: center;
}

.ruler_num0 {
  left: 0;
}

.ruler_num1 {
  left: 20%;
}

.ruler_num2 {
  left: 40%;
}

.ruler_num3 {
  left: 60%;
}

.ruler_num4 {
  left: 80%;
}

.ruler_num5 {
  left: 100%;
}

.ruler_begin {
  position: absolute;
  left: -4px;
  top: 0;
  width: 4px;
  background: rgb(58, 98, 215);
  height: 100%;
  border-top: 4px solid rgb(58, 98, 215);
}

.mapMeasure_containers .ruler_item {
  width: 20%;
  height: 100%;
  border-top: 4px solid rgb(58, 98, 215);
  position: relative;
  float: left;
}

.mapMeasure_containers .ruler_item::after {
  content: "";
  position: absolute;
  right: 0px;
  top: 0;
  width: 4px;
  background: rgb(58, 98, 215);
  height: 100%;
}

.message .el-dialog__body {
  padding-bottom: 8px;
  border-bottom: 1px solid #e9ecef;
  border-top: 1px solid #e9ecef;
}

.viewer {
  height: 100%;
  width: 100%;
}

.zoomVlaueDiv-listContainers {
  animation-name: hide;
  animation-duration: 3s;
  /* 动画持续时间 */
  animation-fill-mode: forwards;
}

.zoomVlaueDiv-list {
  position: absolute;
  top: -12px;
  right: 50px;
  height: 224px;
  justify-content: space-between;
  display: flex;
  flex-direction: column-reverse;
  align-items: center;

}

/* 定义动画 */
@keyframes hide {
  0% {
    opacity: 1;
  }

  90% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}

#zoomSlider:hover .zoomVlaueDiv-listContainers {
  display: block;
  opacity: 1;
  animation-name: ''

    /* 动画结束后保持最后一帧状态 */
}

.zoomVlaueDiv-right {
  width: 40px;
  line-height: 24px;
  text-align: center;
  height: 24px;
  font-size: 14px;
  background: rgb(58, 98, 215);
  color: #fff;
  position: relative;
  cursor: pointer;
}

.zoomVlaueDiv-right::after {
  content: "";
  border-top: 12px solid transparent;
  /* 控制角度，值越大，角度越大 */
  border-bottom: 12px solid transparent;
  /* 控制角度，值越大，角度越大 */
  border-left: 12px solid rgb(58, 98, 215);
  /* 右边框控制边长，值越大边越长 */
  position: absolute;
  right: -12px;
  /* left值与右边框相等取反，例如右边框值为20px，left值为-20px */
  top: 0;

}

.zoomVlaueDiv {
  position: absolute;
  left: 50px;
  width: 60px;
  line-height: 24px;
  text-align: center;
  height: 24px;
  background: rgb(58, 98, 215);
  color: #fff;
}

.zoomSlider .el-slider__button {
  height: 8px !important;
  border-radius: 0px !important;
  border: 1px solid #333;
}

.zoomSlider .el-slider__button::after {
  content: "";
  background-color: red;
  height: 4px;
  width: 10px;
  line-height: 2px;
  display: block;
  position: relative;
  left: 3px;
  border-radius: 4px;
  top: 2px;
}

.zoomSlider .el-slider__runway {
  background-color: #999;
}

/*左三角*/
.zoomVlaueDiv::after {
  content: "";
  border-top: 12px solid transparent;
  /* 控制角度，值越大，角度越大 */
  border-bottom: 12px solid transparent;
  /* 控制角度，值越大，角度越大 */
  border-right: 12px solid rgb(58, 98, 215);
  /* 右边框控制边长，值越大边越长 */
  position: absolute;
  left: -12px;
  /* left值与右边框相等取反，例如右边框值为20px，left值为-20px */
  top: 0;

}

.annotation-image-box {
  position: fixed;
  width: 80%;
  margin-left: 10%;
  margin-right: 10%;
  height: 250px;
  background-color: rgba(0, 0, 0, 0.5);
}

.overlay-info {
  /* text-align: center; */
  /* padding: 5px 10px; */
  color: #000;
  width: 1600px;
  height: 40px;
  line-height: 40px;
  position: fixed;
  top: 0px;
  left: calc((100% - 1600px) / 2);
  left: -webkit-calc((100% - 1600px) / 2);
  z-index: 4;
  /* background: #ffffff; */
  /* background-color: rgba(255, 255, 255, 0.4); */
  overflow-x: auto;
  font-size: 14px;
  /* border-top-right-radius: 18px; */
  /* border-top-left-radius: 18px; */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 50px;
  padding-right: 50px;
}

#zoomSlider {
  height: 200px;
  display: flex;
  position: absolute;
  left: 60px;
  bottom: 150px;
  z-index: 3;
  width: 160px;
  cursor: pointer;
}

#zoomSlider .bar {
  height: 100%;
  position: absolute;
  cursor: pointer;
  width: 30px;
  height: 25px;
  border-radius: 4px;
  text-align: center;
  line-height: 25px;
  background: rgba(0, 0, 0, 0.3);
  font-size: 14px;
  color: #ffffff;
  z-index: 9;
}

#rightToolbar {
  width: 30px;
  display: grid;
  z-index: 1000;
  height: 100%;
}

#rightToolbar .bar {
  position: unset;
  cursor: pointer;
  width: 30px;
  height: 20px;
  border-radius: 4px;
  text-align: center;
  line-height: 20px;
  background: rgba(0, 0, 0, 0.2);
  font-size: 14px;
  color: #ffffff;
}

.panActive {
  color: #ffffff !important;
}

#disc {
  position: absolute;
  right: 45px;
  bottom: 25px;
  z-index: 2;
}


.suspicious-round {
  display: inline-block;
  vertical-align: middle;
  width: 30px;
  height: 30px;
  border-radius: 30px;
}


.displayregion {
  background: rgba(255, 255, 255, 0.4) !important;
}
</style>
